﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MedicalSystem.SmartReport.Access;
using MedicalSystem.SamrtReport.BusinessEntity;
using System.IO;
using System.Diagnostics;
using MedicalSystem.SmartReport.Viewer;
using MedicalSystem.SamrtReport.Library;

namespace MedicalSystem.SamrtReport.Tools
{
    public partial class ImportExportWizard : Form
    {
        public ImportExportWizard()
        {
            InitializeComponent();
        }
        private OperationType _operactionType;
        private string _providerName = string.Empty;

        private void ImportExportWizard_Load(object sender, EventArgs e)
        {
            this.tabControl1.TabPages.Clear();
            this.tabControl1.TabPages.Add(this.SelectTypetabPage);

            this.comboBox1.Items.Clear();
            for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
            {
                this.comboBox1.Items.Add(ConfigurationManager.ConnectionStrings[i].Name);
            }
            CustomFormHepler.ShowForm(this);
        }

     

        private void NextButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab == this.SelectTypetabPage)
            {
                if (this.NewRadioButton1.Checked)
                {
                    _operactionType = OperationType.ImportNew;
                }
                else if (UpdateRadioButton2.Checked)
                {
                    _operactionType = OperationType.ImportUpdated;
                }
                else
                {
                    _operactionType = OperationType.Export;
                }
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectDataConntabPage);
                this.PreviousButton.Enabled = true;
                comboBox1_SelectedIndexChanged(this, EventArgs.Empty);
            }
            else if (this.tabControl1.SelectedTab == this.SelectDataConntabPage)
            {
                this.tabControl1.TabPages.Clear();
                this.NextButton.Enabled = false;
               
                this.PreviousButton.Enabled = true;
                if (this._operactionType == OperationType.ImportNew)
                {
                    this.FinishButton.Enabled = true;
                    this.tabControl1.TabPages.Add(this.NewImportTabPage);
                }
                else if (this._operactionType == OperationType.ImportUpdated)
                {
                    this.tabControl1.TabPages.Add(this.UpdateImportTabPage);
                    InitalizeTabPage(this.listBox1);
                }
                else
                {
                    this.tabControl1.TabPages.Add(this.ExportTabPage);
                    InitalizeTabPage(this.listBox2);
                }
               
            }
            
        }
        private void InitalizeTabPage(ListBox listbox)
        {

            IDatabase database = DatabaseFactory.CreateDatabase(this.richTextBox.Text, this._providerName);
            this.FinishButton.Enabled = false;
            try
            {
                using (AsyncWorker asyncWorker = new AsyncWorker(listbox))
                {
                    asyncWorker.DoWork += delegate(object sender, DoWorkEventArgs e)
                    {
                        e.Result = database.GetTemplate().Template;
                    };
                    asyncWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        listbox.DataSource = e.Result as SmartReportTemplate.TemplateDataTable;
                        this.FinishButton.Enabled = true;
                    };
                    asyncWorker.Run();
                }
            }
            catch (SmartReportException e)
            {

                Trace.WriteLine(e.InnerException.Message);
                this.FinishButton.Enabled = false;
            }
           
           

        }
        private void PreviousButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab == this.SelectDataConntabPage)
            {
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectTypetabPage);
                this.PreviousButton.Enabled = false;
                this.NextButton.Enabled = true;
            }
            else 
            {
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectDataConntabPage);
                this.PreviousButton.Enabled = true;
                this.NextButton.Enabled = true;
                this.FinishButton.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.richTextBox.Visible == false)
            {
                this.richTextBox.Visible = true;
                this.button2.Text = "-";
            }
            else
            {
                this.richTextBox.Visible = false;
                this.button2.Text = "+";
            }
        }

        private void NewConnectionButton_Click(object sender, EventArgs e)
        {
            DataConnectionSettingFrm dataConnectionSetting = new DataConnectionSettingFrm();
            if (dataConnectionSetting.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dataConnectionSetting.ConnectionStringName))
                {
                    this.comboBox1.Items.Add(dataConnectionSetting.ConnectionStringName);
                    this.comboBox1.Text = dataConnectionSetting.ConnectionStringName;
                }

                this.richTextBox.Text = dataConnectionSetting.ConnectionString;
                this._providerName = dataConnectionSetting.ProviderName;
                this.NextButton.Enabled = true;

            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.comboBox1.Text))
            {
                this.richTextBox.Text = string.Empty;
                this.NextButton.Enabled = false;
                return;
            }
            if (ConfigurationManager.ConnectionStrings[this.comboBox1.Text] != null)
            {
                this.richTextBox.Text = ConfigurationManager.ConnectionStrings[this.comboBox1.Text].ConnectionString;
                this._providerName = ConfigurationManager.ConnectionStrings[this.comboBox1.Text].ProviderName;
                this.NextButton.Enabled = true;
            }
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.richTextBox1.Visible == false)
            {
                this.richTextBox1.Visible = true;
                this.button3.Text = "-";
            }
            else
            {
                this.richTextBox1.Visible = false;
                this.button3.Text = "+";
            }
        }

        private void FinishButton_Click(object sender, EventArgs e)
        {
 
            if (this.tabControl1.SelectedTab == this.NewImportTabPage)
            {
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    this.errorProvider1.SetError(textBox1, "请输入新创建的表单名称");
                    return;
                }
                if (string.IsNullOrEmpty(this.richTextBox1.Text))
                {
                    this.errorProvider1.SetError(richTextBox1, "请导入新创建的设计模版");
                    if (this.richTextBox1.Visible == false)
                        button3_Click(this, EventArgs.Empty);
                    return;
                }

                IDatabase database = DatabaseFactory.CreateDatabase(this.richTextBox.Text, this._providerName);
                SmartReportTemplate template = database.GetTemplate();

                foreach (SmartReportTemplate.TemplateRow row in template.Template)
                {
                    if (row.ReportName.ToLower() == this.textBox1.Text.ToLower())
                    {
                        this.errorProvider1.SetError(textBox1, "已存在相同的表单名称");
                        return;
                    }
                }

                SmartReportTemplate.TemplateRow created = template.Template.NewTemplateRow();
                created.ReportName = this.textBox1.Text;
                created.HospitalName = this.textBox2.Text;
                created.ReportTemplate = this.richTextBox1.Text;
                created.CreateTime = DateTime.Today;
                created.LastUpdateTime = DateTime.Today;
                created.ReportTemplateID = GetRandomKey();

                template.Template.AddTemplateRow(created);
                database.SaveTemplate(template);
                Trace.WriteLine(string.Format("已导入名为{0}的表单设计模版", this.textBox1.Text));

            }
            else if (this.tabControl1.SelectedTab == this.UpdateImportTabPage)
            {
                if (this.listBox1.SelectedValue == null)
                {
                    this.errorProvider1.SetError(listBox1, "请选择将修改设计模版内容的表单");
                    return;
                }
                if (string.IsNullOrEmpty(this.richTextBox2.Text))
                {
                    this.errorProvider1.SetError(richTextBox2, "请导入新修改的设计模版");
                    if(this.richTextBox2.Visible==false)
                        button5_Click(this,EventArgs.Empty); 
                    return;
                }

               
                SmartReportTemplate.TemplateDataTable template= this.listBox1.DataSource as SmartReportTemplate.TemplateDataTable;
               
                if (template.DataSet.HasChanges())
                {
                    IDatabase database = DatabaseFactory.CreateDatabase(this.richTextBox.Text, this._providerName);
                    database.SaveTemplate(template.DataSet as SmartReportTemplate);
                    Trace.WriteLine(string.Format("已保存修改后的表单"));
                }
               
            }
            this.DialogResult = DialogResult.OK;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (this.richTextBox2.Visible == false)
            {
                this.richTextBox2.Visible = true;
                this.button5.Text = "-";
            }
            else
            {
                this.richTextBox2.Visible = false;
                this.button5.Text = "+";
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ImportUpdateButton.Enabled = this.listBox1.SelectedItem != null;
        }

        private void ImportUpdateButton_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.richTextBox2.Text = File.ReadAllText(openFileDialog1.FileName, Encoding.UTF8);
                SmartReportTemplate.TemplateDataTable template = this.listBox1.DataSource as SmartReportTemplate.TemplateDataTable;
               
                int reportTemplateId = Convert.ToInt32(this.listBox1.SelectedValue);

                foreach (SmartReportTemplate.TemplateRow row in template)
                {
                    if (row.ReportTemplateID == reportTemplateId)
                    {
                        row.ReportTemplate = this.richTextBox2.Text;
                        row.LastUpdateTime = DateTime.Today;
                        Trace.WriteLine(string.Format("已修改{0}的表单设计模版", row.ReportName));
                        
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName, Encoding.UTF8);
            }
        }

       

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ExportButton.Enabled = listBox2.SelectedItem != null;
        }

        private void ExportButton_Click(object sender, EventArgs e)
        {
            if (listBox2.SelectedItem == null)
                return;
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DataRowView rowView = listBox2.SelectedItem as DataRowView;
               SmartReportTemplate.TemplateRow  templateRow= rowView.Row as SmartReportTemplate.TemplateRow;
               if (templateRow == null)
                    Trace.WriteLine("未能导出模版文档");
                else
                    System.IO.File.WriteAllText(this.saveFileDialog1.FileName, templateRow.ReportTemplate, Encoding.UTF8);

            }
           


        }

        private void SelectTypetabPage_Click(object sender, EventArgs e)
        {

        }

        private int GetRandomKey()
        {
            long tick = DateTime.Now.Ticks;

            Random random = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
            return random.Next(0, int.MaxValue);

        }

        private void SelectDataConntabPage_Click(object sender, EventArgs e)
        {

        }
    }

    public enum OperationType
    {
        ImportNew,
        ImportUpdated,
        Export
    }
}
